<?php

namespace App\Services\MiniprogramToGame;

use App\Models\MtgGameFaqData;
use App\Models\MtgGameFaqType;
use App\Services\ServiceBase;

class GameFaqService extends ServiceBase
{
    public function getInfo($game_id)
    {
        $time = time();
        $typelist = MtgGameFaqType::where('game_id', $game_id)->get();
        $list = [];
        foreach ($typelist as $val) {
            $list[] = [
                'id'       => $val->id,
                'name'     => $val->name,
                'icon_url' => "{$val->icon_url}?v={$time}",
            ];
        }

        $data = [
            'type_list'  => $list,
            'can_share'  => 1,
            'top_img'    => "https://cdn-resource.tkungame.com/mtg/gamefaq/top.png?v={$time}",
            'share_img'  => "https://cdn-resource.tkungame.com/mtg/gamefaq/share-icon.png?v={$time}",
        ];
        return $data;
    }

    private function formatNumber($number)
    {
        if ($number <= 1000) {
            return 0;
        } elseif ($number <= 10000) {
            return round($number / 1000, 1) . '千';
        } elseif ($number <= 100000000) {
            return round($number / 10000, 0) . '万';
        }
    }

    public function getList($params)
    {
        $game_id  = $params['game_id'];
        $page  = $params['page'] ?? 1;
        $limit = $params['limit'] ?? 100;
        $page  = ($page - 1) * $limit;
        $is_search = $params['is_search'] ?? 0;

        $query = MtgGameFaqData::where('game_id', $game_id);

        // 指定类型搜索
        $type_id = $params['type_id'] ?? 0;
        if (!empty($type_id)) {
            $query->where('type_id', $type_id);
        }

        // title搜索
        $title = $params['title'] ?? '';
        if (!empty($title)) {
            $query->where('title', 'like', "%{$title}%");
        }

        $list = [];

        if ($is_search == 1) {
            $data = $query->orderBy('hot_value', 'desc')->offset($page)->limit($limit)->get();
        } else {
            $data = $query->offset($page)->limit($limit)->get();
        }

        $typelist = MtgGameFaqType::where('game_id', $game_id)->get()->keyBy('id');

        foreach ($data as $index => $val) {
            $tmp = [
                'type_id'   => $val->type_id,
                'type_name' => $typelist[$val->type_id]['name'],
                'date'      => date('Y-m-d', $val->create_time),
                'title'     => $val->title,
                'desc'      => $val->desc,
                'url'       => config('app.url') . "/mtg/gamefaq/article/" . $val->id,
                'hot_index' => $page + $index + 1,
                'hot_value' => $this->formatNumber($val->hot_value),
            ];
            $list[] = $tmp;
        }

        return $list;
    }
}
